import CryptoJS from 'crypto-js'
import dayjs from 'dayjs'
import customParseFormat from 'dayjs/plugin/customParseFormat.js'
import utc from 'dayjs/plugin/utc.js'
import timezone from 'dayjs/plugin/timezone.js'
import axios from 'axios'

dayjs.extend(customParseFormat)
dayjs.extend(utc)
dayjs.extend(timezone)

//讯飞不同功能,host不同,生成signature的tmp字段未尾的post/get不同

const APPID = '5f711f96'
const APISecret = 'YTI5MDBiODBiYjgxNjBiNmRmMTNhOTE1'
const APIKey = '046774733dfbfb0e4e3b9f4317101583'
const host = 'api.xf-yun.com'

//鉴权url
function getAuthorizationUrl() {
    //获取鉴权时间 date
    const RFC1123_FORMAT = 'ddd, DD MMM YYYY HH:mm:ss [GMT]'
    const date = dayjs().utc().format(RFC1123_FORMAT)
    console.log(date)

    //拼接生成字符串tmp
    const tmp = `host: ${host}\ndate: ${date}\nPOST /v1/private/sf8e6aca1 HTTP/1.1` //注意空格必须保留

    //tmp加密获取smp_sha
    const hash = CryptoJS.HmacSHA256(tmp, APISecret)
    console.log(hash)

    //tmp_sha进行base64编码生成signature
    const signature = CryptoJS.enc.Base64.stringify(hash)
    console.log('signature', signature)

    //获得 authorization_origin
    const authorization_origin = `api_key="${APIKey}", algorithm="hmac-sha256", headers="host date request-line", signature="${signature}"`

    console.log(authorization_origin)

    //获得authorization
    const authorization = Buffer.from(authorization_origin).toString('base64')
    console.log('authorization', authorization)
    const url = `https://api.xf-yun.com/v1/private/sf8e6aca1?authorization=${authorization}&host=${host}&date=${encodeURIComponent(date).replace(/%20/g, '+')}`
    console.log(url)
    return url
}

export async function getText(base64) {
    const url = getAuthorizationUrl()

    const res = await axios.post(url, {
        header: {
            app_id: APPID,
            status: 3,
        },
        parameter: {
            sf8e6aca1: {
                category: 'ch_en_public_cloud',
                result: {
                    encoding: 'utf8',
                    compress: 'raw',
                    format: 'json',
                },
            },
        },
        payload: {
            sf8e6aca1_data_1: {
                encoding: 'jpg',
                status: 3,
                image: base64,
            },
        },
    })
    const buffer = Buffer.from(res.data.payload.result.text, 'base64')
    const obj = JSON.parse(buffer.toString('utf-8'))

    let textResult = ''
    obj.pages.forEach((item) => {
        if (item.lines) {
            item.lines.forEach((line) => {
                if (line.words) {
                    line.words.forEach((word) => {
                        textResult += word.content
                    })
                }
            })
        }
    })
    // pages[n].lines[n].words[n].content
    return textResult
}
